layui.use(['layer', 'form', 'table', 'configs', 'template'], function () {
    var $ = layui.jquery,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        template = layui.template,
        config = layui.configs;

    //全局变量：表格列
    var cols = [
        {field: 'userName', title: '用户名'}
        , {field: 'nickName', title: '昵称'}
        , {field: 'roleName', title: '该用户角色名'}
        , {field: 'roleRemark', title: '角色备注'}
        , {fixed: 'right', title: '操作', width: 100, align: 'center', toolbar: '#rowOperate'}
    ];

    //获取表格数据
    getTableData();

    function getTableData() {
        $.ajax({
            url: config.motorBaseUrl + "/sys/getUsers/v1.0",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    renderTable(cols, result.data);
                } else {
                    layer.msg(result.stateMsg);
                }

            }
        })
    }

    //渲染表格
    function renderTable(cols, data) {
        table.render({
            elem: '.usersTable'
            , id: 'users-table'
            , data: data
            , autoSort: false
            , toolbar: '#toolbarUsers'
            , defaultToolbar: ['filter']
            , cols: [cols]
            , page: {
                layout: ['prev', 'page', 'next', 'count', 'skip', 'limit'] //自定义分页布局
                , groups: 1 //只显示 5 个连续页码
                , first: false
                , last: false
                , limits: [10, 20, 50, 100, 500]
            }
            , limit: 10
            , loading: true
        });
    }

    //头工具栏事件--新增
    table.on('toolbar(usersTable)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        var event = obj.event;
        if (event === 'addUsers') { //新增
            var layerIdx = layer.open({
                type: 1,
                title: "新增用户",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#newAdd').html(),
                success: function (layero, index) {
                    getRoleData(layero);
                }
            });
            form.on('submit(AddForm)', function (res) {
                console.log(res.field) //当前容器的全部表单字段，名值对形式：{name: value}
                addUsers(res.field);
                layer.close(layerIdx);
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            });
            $(".addUsers button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        }
    });


    //监听工具条
    table.on('tool(usersTable)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'del') { //删除
            layer.confirm('真的删除吗？', function (index) {
                layer.close(index);
                deleteUsers(obj, data);
            });
        } else if (layEvent === 'edit') { //编辑
            var layerIdx = layer.open({
                type: 1,
                title: "编辑",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#rowEdit').html(),
                success: function (layero, index) {
                    getRoleData(layero, function(){
                        form.val('rowEditForm',data);
                    });
                }
            });
            form.val("rowEditForm", data);
            form.on('submit(rowEditForm)', function (res) {
                //console.log(res.field) //当前容器的全部表单字段，名值对形式：{name: value}
                updateUsers(obj, res.field);
                layer.close(layerIdx);
                return false;
            });
            $(".editUsers button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        }
    });

    //新增
    function addUsers(dataObj) {
        $.ajax({
            url: config.platformBaseUrl + "/user/userAdd/v1.0",
            type: "post",
            datatype: "json",
            data: dataObj,
            success: function (result) {
                if (result.stateCode == 0) {
                    getTableData();
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //删除
    function deleteUsers(obj, data) {
        $.ajax({
            url: config.platformBaseUrl + "/user/delete/v1.0",
            type: "post",
            datatype: "json",
            data: data,
            success: function (result) {
                if (result.stateCode == 0) {
                    refreshTable('delete', obj);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    };

    //更新
    function updateUsers(obj, data) {
        $.ajax({
            url: config.platformBaseUrl + "/user/edit/v1.0",
            type: "post",
            datatype: "json",
            data: data,
            success: function (result) {
                if (result.stateCode == 0) {
                    getTableData();
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //查全部角色
    function getRoleData(layero, callback) {
        $.ajax({
            url: config.motorBaseUrl + "/sys/getRoles/v1.0",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    // var list = result.data;
                    // var roleList = [];
                    // for(let k in list){
                    //     if(list[k] != null){
                    //         roleList.push(list[k][0]);
                    //     }
                    // }
                    layero.find($(".role-sel")).html(template("role-tpl", result));
                    form.render();
                    callback && callback();
                } else {
                    layer.msg(result.stateMsg);
                }
            }
        })
    }

    function tableReload() {
        table.reload("users-table", {
            url: config.motorBaseUrl + "/sys/getRoles/v1.0"
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.stateCode, //解析接口状态
                    "msg": res.stateMsg, //解析提示文本
                    "data": res.data //解析数据列表
                };
            }
        })
    };

    function refreshTable(type, obj, data) {
        if (type == "update") {
            obj.update(data); //同步更新缓存对应的值
        } else if (type == "delete") {
            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
        }
    };

});
